package com.jrfid.smartcabinet.demo.utils

import com.xuhao.didi.core.protocol.IReaderProtocol
import com.xuhao.didi.socket.client.sdk.OkSocket
import com.xuhao.didi.socket.client.sdk.client.ConnectionInfo
import com.xuhao.didi.socket.client.sdk.client.OkSocketOptions
import com.xuhao.didi.socket.client.sdk.client.action.SocketActionAdapter
import com.xuhao.didi.socket.client.sdk.client.connection.IConnectionManager
import java.nio.ByteOrder

object TCPConnectUtils {

    /**
     * 连接设备
     * @param type 0:rfid,1:nfc,2:指静脉
     */
    private fun connectDevice(type: Int, ip: String, port: Int, listener: SocketActionAdapter?): IConnectionManager {
        val manager = OkSocket.open(ConnectionInfo(ip, port))
        val builder = OkSocketOptions.Builder(manager.option).setConnectTimeoutSecond(10)
        when (type) {
            0 -> {
                builder.setReaderProtocol(object : IReaderProtocol {
                    override fun getHeaderLength(): Int {
                        return 2
                    }

                    override fun getBodyLength(header: ByteArray, byteOrder: ByteOrder?): Int {
                        return KTDataUtils.hexToInt(KTDataUtils.byteToHex(header[1]))
                    }
                })
            }
            1 -> {
                builder.setReaderProtocol(object : IReaderProtocol {
                    override fun getHeaderLength(): Int {
                        return 2
                    }

                    override fun getBodyLength(header: ByteArray, byteOrder: ByteOrder?): Int {
                        return 8
                    }
                })
            }
            2 -> {

            }
        }
        manager.option(builder.build())
        if (listener != null)
            manager.registerReceiver(listener)
        manager.connect()
        return manager
    }

    fun connectDevice(ip: String, port: Int, listener: SocketActionAdapter?): IConnectionManager {
        val manager = OkSocket.open(ConnectionInfo(ip, port))
        if (listener != null)
            manager.registerReceiver(listener)
        if (!manager.isConnect)
            manager.connect()
        return manager
    }

    fun connectRFIDDevice(ip: String?, port: Int?, listener: SocketActionAdapter?): IConnectionManager {
        return connectDevice(0, ip ?: "", port ?: 4001, listener)
    }

    fun connectNFCDevice(ip: String?, port: Int?, listener: SocketActionAdapter?): IConnectionManager {
        return connectDevice(1, ip ?: "", port ?: 4196, listener)
    }

    fun connectFingerDevice(ip: String, port: Int, listener: SocketActionAdapter?): IConnectionManager {
        return connectDevice(2, ip, port, listener)
    }

    fun getConnectionManager(ip: String, port: Int): IConnectionManager {
        return OkSocket.open(ConnectionInfo(ip, port))
    }
}